package com.ty.service;

import cn.smart.core.util.UserContext;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ty.dao.WarehouseDao;
import com.ty.entity.Warehouse;
import com.ty.entity.WarehouseQuery;
import com.ty.enums.WarehouseStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class WarehouseService {

    @Autowired
    private WarehouseDao warehouseDao;

    //缺点： 1. 所有方方法的返回的类型PageInfo  2. 返回信息字段太多

    public List<Warehouse> select (WarehouseQuery query){
        LambdaQueryWrapper<Warehouse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(query.getId() != null,Warehouse::getId,query.getId());
        queryWrapper.eq(query.getStatus() != null,Warehouse::getStatus,query.getStatus());
        List<Warehouse> list = warehouseDao.selectList(queryWrapper);
        return list;
    }

    public int insert (Warehouse warehouse){
        return warehouseDao.insert(warehouse);
    }

    public int update(Warehouse warehouse) {
        LambdaUpdateWrapper<Warehouse> updateWapper = Wrappers.lambdaUpdate(Warehouse.class);
        updateWapper.set(warehouse.getStatus() != null, Warehouse::getStatus, warehouse.getStatus());
        updateWapper.set(warehouse.getName() != null, Warehouse::getName, warehouse.getName());
        updateWapper.set(warehouse.getBrief() != null, Warehouse::getBrief, warehouse.getBrief());
        updateWapper.set(warehouse.getSeq() != null, Warehouse::getSeq, warehouse.getSeq());
        updateWapper.set(warehouse.getImg() != null,
                Warehouse::getImg,
                warehouse.getImg(),"typeHandler=com.ty.typehandler.JsonTypeHandler"
        );
        updateWapper.set( Warehouse::getLastUpdateBy, UserContext.get().getNickName());
        updateWapper.eq( Warehouse::getId, warehouse.getId());
        return warehouseDao.update(updateWapper);
    }
    public int delete(Integer id) {
        LambdaUpdateWrapper<Warehouse> updateWapper = Wrappers.lambdaUpdate(Warehouse.class);
        updateWapper.set( Warehouse::getStatus, WarehouseStatus.OFF_SHELF.getCode());
        updateWapper.eq( Warehouse::getId,id);
        return warehouseDao.update(updateWapper);
    }

}
